<template>
    <vue-tribute ref="tribute" :options="tributeOption"  style="height:100%;margin-top: 10px">
        <div id="chatArea" ref="chatArea" class="chat-box__input" style="height: 100%;width: 100%;"
             v-html="tributeText"
             @tribute-replaced="tributeReplaced"
        ></div>
    </vue-tribute>
</template>
<script>
import {Dialog,Util} from "@lowcode/jpaas-common-lib"
import VueTribute from "./tribute/vueTribute";


export default {
    name: 'rx-tribute',
    components: {
        VueTribute
    },
    props: {
        layerid: String,
        lydata: Object,
        destroy: Function,
    },
    data() {
        return {
            tributeOption: {
                // 输入框@配置项
                trigger: "@",
                values: this.remoteSearch,
                positionMenu: true,
                lookup: function (person, mentionText) {
                    return person.value + person.key;
                },
                //设置选择后的div属性
                selectTemplate:function (item){
                    return (
                        '<span class="tribute-mention" userid="'+item.original.key+'">' +
                        item.original.value +'</span>'
                    );
                },
                menuContainer: this.$refs['chatArea'],
            },
            tributeText: '', // 聊天窗html内容
            currSelectRy: {}, // 当前选中的人员信息
            atRyList: [], // 所有选中的
        }
    },
    mounted() {
        // 注册键盘监听事件
        this.$refs.chatArea.addEventListener('keydown', this.handleChatAreaEvent);
    },
    destroyed() {
        // 移除监听事件
        // 不再需要监听时，记得移除事件监听器
        this.$refs.chatArea.removeEventListener('keydown', this.handleChatAreaEvent);
    },
    created() {
    },
    methods: {
        handleInnerHtml(innerHTML,innerText){
            if("@"===innerHTML){
                return "";
            }
            if(this.isEndDiv(innerHTML)){
                return innerHTML.replace(/@<\/div>\s*$/i, '<\/div>');
            }
            return  innerHTML.replace(/@\s*$/, '');
        },
        isEndDiv(innerHTML){
            const isEndsWithAtDiv = /@<\/div>\s*$/.test(innerHTML);
            return isEndsWithAtDiv;
        },
        async remoteSearch(text, cb){
            debugger;
            let cbJson = await this.getUserList();
            if(!cbJson.success){
                return;
            }
            let chatArea =this.$refs.chatArea;
            let allStr ="";
            for(let i=0;i<cbJson.data.length;i++){
                let user = cbJson.data[i];
                this.atRyList.push(user.userId);
                let spanStr = '<span class="tribute-mention" userid="' + user.userId + '">@'+user.fullName+'</span>';
                allStr += spanStr+"&nbsp";
            }
            this.tributeText = this.handleInnerHtml(chatArea.innerHTML,chatArea.innerText) + allStr;
        },
        async getUserList(){
            let self_=this;
           return new Promise(resolve => {
               var conf = {curVm: self_, data: {}, widthHeight: ['1024px', '580px']};
              Dialog.openUserDialog(conf, function (self, users) {
                  let cbJson={
                      success:false,
                      divIdKey:"chatArea",
                      data:[]
                  }
                   if(!users || users.length==0){
                       resolve(cbJson)
                   }
                   for (var i = 0; i < users.length; i++) {
                       var user = users[i];
                       user.key = user.userId;
                       user.value = user.fullName;
                   }
                  cbJson.success=true;
                  cbJson.data = users;
                  resolve(cbJson)
               });
           })
        },
        getSelectUsers(innerHTML){
            let users = [];
            // 将字符串转为DOM节点列表
            let parser = new DOMParser();
            let doc = parser.parseFromString(innerHTML, "text/html");

            // 获取所有 class="tribute-mention" 的元素
            let mentionElements = doc.querySelectorAll('.tribute-mention');
            // 遍历并打印每个元素的信息
            mentionElements.forEach((element) => {
                let userId = element.getAttribute('userid');
                if(!this.isContainUserId(users,userId)){
                    users.push(userId);
                }
            });
            return users;
        },
        isContainUserId(users,addUserId){
            if(users.length==0){
                return false;
            }
            let isContain =users.find(userId=>{return userId == addUserId});
            if(isContain){
                return true;
            }
            return false;
        },
        /**
         * @desc 监听@输入事件
         */
        handleChatAreaEvent(e){
            // 重写backspace, 1、删除文字时，不能删除前面的空标签。2、标签可以直接删除。
            if (e.keyCode === 8) {
                let selection = window.getSelection();
                // 如果光标当前位置是@区域，移除当前@所属dom
                if (selection.anchorNode.parentNode.className == 'tribute-mention') {
                    let curr_node = selection.anchorNode.parentNode;
                    // 获取当前元素在父元素的位置
                    let child = selection.anchorNode.parentNode;
                    let i = 0; // 当前dom在父节点中的位置
                    let index = 0; // 在@人员列表中的位置

                    while ((child = child.previousSibling) != null) i++;

                    index = i && i - 2 >= 0 ? i - 2 : 0;
                    // 从dom中移除
                    curr_node.remove();
                    // 人员列表中数据移除
                    this.atRyList.splice(index, 1);
                    this.currSelectRy = {};
                }
            }
        },
        tributeReplaced(e){
            if (e.detail && e.detail.item && e.detail.item.original) {
                this.currSelectRy = e.detail.item.original;
                this.atRyList.push(this.currSelectRy);
            }
        },

        i18n(name,text,key){
            return this.$ti18(name,text,"bpmTask",key);
        },
        /**
         * 获取沟通用户数据
         */
        getLinkup() {
            let chatArea =this.$refs.chatArea;
            let users = this.getSelectUsers(chatArea.innerHTML);
            if(users.length>0){
                 return users.join(",");
            }
            return "";
        },
        /**
         * 获取意见
         */
        getOpinion() {
            let chatArea =this.$refs.chatArea;
            return chatArea.innerText;
        },
        setTributeText(value){
            let chatArea =this.$refs.chatArea;
            this.tributeText = chatArea.innerHTML + value;
        },
    }
}
</script>
<style>
.tribute-container {
    position: fixed!important;
    top: 0;
    left: 0;
    height: auto;
    max-height: 300px;
    max-width: 500px;
    overflow: auto;
    display: block;
    z-index: 999999;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(#000, 0.13);
}
</style>
<style scoped>
.chat-box__input {
    text-align: left;
    height: 130px;
    overflow: auto;
    color: #333333;
    border:1px solid #ddd;
    border-radius: 5px;
}
.chat-box__input:focus {
    outline: 0;
    box-shadow: 0 0 0 2px rgba(24,144,255,.2) !important;
    border: 1px solid #40a9ff;
}


ul {
    padding: 10px;
    background-color: #fff;
}

li {
    list-style: none;
    line-height: 36px;
    margin: 0;
    font-size: 14px;
    color: #606266;
    cursor: pointer;
    outline: none;
}

li.highlight,
li:hover {
    background-color: #ecf5ff;
    color: #66b1ff;
}

/deep/.tribute-mention {
    display: inline-block;
    padding: 1px 5px;
    background-color: rgba(200, 221, 251, 0.45);
    color: #4090ff;
}
</style>